import React, { useState } from 'react';
import { useHistory, useParams, useLocation } from 'react-router-dom';
// import { useRequest, useTimeout } from 'ahooks';
import { useRequest } from 'ahooks';
import { Helmet } from 'react-helmet';
import { empty } from '@/common/utils';
import { getRoomDetail, getRoomDetailByUserId } from '@/service/live';
import Loading from '@/components/Loading';
import BottomDownload from '@/components/BottomDownload';
import DialogDownload from '@/components/DialogDownload';
import Toast from '@/components/Toast';
import Header from './components/Header';
import Player from './components/Player';
import Tabs from './components/Tabs';
import Message from './components/Message';

import styles from './style/index.scss';

const LiveRoomPageMain = ({ data }) => {
  const [visibleDialogDownload, setVisibleDialogDownload] = useState(false);

  const onOpenDialogDownloadHandle = () => {
    setVisibleDialogDownload(true);
  };

  const onCloseDialogDownloadHandle = () => setVisibleDialogDownload(false);

  // 两分钟弹框一次下载
  empty(onOpenDialogDownloadHandle, visibleDialogDownload ? undefined : 2 * 60 * 1000);

  const anchornickname = data?.nickname;

  return (
    <main className={styles.container}>
      <Helmet>
        <title>{`鑫球直播-${anchornickname}直播间_${anchornickname}直播解说_${anchornickname}的直播频道`}</title>
        <meta name="keywords" content={`${anchornickname}_${anchornickname}直播地址_足球高清直播_nba篮球免费高清视频_体育比赛解说`} />
        <meta
          name="description"
          content="鑫球直播为体育做足准备-提供高清免费NBA直播_足球直播包括世界杯直播_英超_法甲_西甲_德甲_意甲_中超_CBA等体育直播_看高清体育直播就来鑫球直播"
        />
      </Helmet>
      <Header />
      <Player data={data} />
      <Tabs fans={data.subscribeCount} userImage={data.headerImg} onItemClick={onOpenDialogDownloadHandle} />
      <div className={styles.message}>
        <Message data={data} />
      </div>
      <BottomDownload />
      <DialogDownload visible={visibleDialogDownload} onClose={onCloseDialogDownloadHandle} />
    </main>
  );
};

const LiveRoomPage = () => {
  const { id } = useParams();
  const { search } = useLocation();
  const history = useHistory();
  const request = () => {
    if (/userId=true/.test(search)) {
      return getRoomDetailByUserId({ userId: id });
    }
    return getRoomDetail([id]);
  };
  const { data, loading } = useRequest(
    () => request(),
    {
      defaultLoading: true,
      refreshDeps: [id],
    },
  );

  const onToastCloseHandle = () => history.replace('/');

  if (loading) return (<Loading />);
  if (!data) return (<Toast visible text="直播间不存在" duration={2000} onClose={onToastCloseHandle} />);

  return (<LiveRoomPageMain data={data} />);
};

export default LiveRoomPage;
